#!/usr/bin/env python3
# coding: utf-8
# vim: fdm=marker fmr={{{,}}} cms=#%s#

import sys, os

from datetime import datetime

from pymongo import Connection
from pymongo import ASCENDING, DESCENDING

from conf import Conf

class App:
    def main(self):
        self.__run()

    def __run(self):
        try:
            conn=Connection(host=Conf.mongodb.host,
                    port=Conf.mongodb.port,
                    network_timeout=10)
            db=conn[Conf.mongodb.database]
        except Exception as e:
            print("db connect fail: %s" % e)
            return

        try:
            __split="----------------------------------------"

            self.__init(db)
            print(__split)

            self.__insert(db)
            print(__split)

            self.__select(db)
            print(__split)

            self.__delete(db)
            print(__split)
        except Exception as e:
            print("fail: %s" % e)

        try:
            conn.close()
        except:
            pass

    def __init(self, db):
        test_users=db.test_users
        test_users.create_index([("id", ASCENDING)], unique=True)
        test_users.create_index([("login", ASCENDING)], unique=True)

        try:
            test_seq=db.test_seq
            test_seq.create_index([("id", ASCENDING)], unique=True)
            test_seq.insert({"id":"test_users", "nextval":101}, safe=True)
        except Exception as e:
            print("%s" % e)

    def __insert(self, db):
        test_seq=db.test_seq
        test_users=db.test_users

        login="PY000001@qq.com"
        user={ "id":100, "update_ts":datetime.now(), "login":login,
            "name":"PY东风", "job":1, "address":"魔都" }
        test_users.update({"login":login}, user, upsert=True, multi=False,
                safe=True)

        users=[]
        for i in range(3):
            seq=test_seq.find_and_modify({"id":"test_users"},
                    {"$inc":{"nextval":1}})
            nextval=seq["nextval"]
            user={
                    "id":nextval, "update_ts":datetime.now(	),
                    "login":"PY%06d@qq.com" % nextval,
                    "name":"PY东风%d" % nextval, "job":2,
                    "address":"PY魔都%d" % nextval
                }
            users.append(user)
        test_users.insert(users, safe=True)

    def __select(self, db):
        test_users=db.test_users

        rs=test_users.find({"job":{"$gte":0}}).sort([("id", DESCENDING)])
        for user in rs:
            print("%d | %s | %s | %s | %d | %s" %
                    (user["id"], user["update_ts"], user["login"],
                     user["name"], user["job"], user["address"]))

    def __delete(self, db):
        test_users=db.test_users

        test_users.remove({"id":100})

if __name__ == "__main__":
    App().main()
